function getCurrentHost(){
  return new Promise(r=>{
    chrome.tabs.query({active:true,currentWindow:true},tabs=>{
      const t=tabs&&tabs[0]
      try{
        const u=new URL(t.url)
        r(u.hostname)
      }catch(e){r('')}
    })
  })
}
async function updateSite(){
  const host=await getCurrentHost()
  document.getElementById('site').textContent=host||'-'
  const input=document.getElementById('domain')
  if(host) input.value=host
}
function toast(msg,type){
  const el=document.getElementById('toast')
  el.className = 'toast' + (type?(' '+type):'')
  el.textContent=msg
  el.style.display='block'
  setTimeout(()=>{el.style.display='none'},1500)
}
function setStatus(status){
  const el=document.getElementById('status')
  el.textContent=status==='TOPMOST'?'ON':status==='NOTOPMOST'?'OFF':status
  el.className='pill '+(status==='TOPMOST'?'ok':'off')
}
function render(){
  chrome.storage.local.get(['autoTopEnabled','whitelist']).then(async s=>{
    document.getElementById('auto').checked=!!s.autoTopEnabled
    await updateSite()
    const wl=Array.isArray(s.whitelist)?s.whitelist:[]
    const list=document.getElementById('list')
    list.innerHTML=''
    const display = showAll ? wl : wl.slice(0,4)
    display.forEach(d=>{
      const chip=document.createElement('div')
      chip.className='chip'
      const text=document.createElement('span')
      text.textContent=d
      const btn=document.createElement('button')
      btn.textContent='×'
      btn.onclick=()=>{
        const nw=wl.filter(x=>x!==d)
        chrome.storage.local.set({whitelist:nw}).then(render)
      }
      chip.appendChild(text)
      chip.appendChild(btn)
      list.appendChild(chip)
    })
    const more=document.getElementById('more')
    if(wl.length>4){
      more.style.display='inline-block'
      more.textContent= showAll ? '收起' : '展开全部'
    }else{
      more.style.display='none'
    }
    chrome.storage.local.get(['pluginStatus']).then(s2=>{
      if(s2.pluginStatus){
        setStatus(s2.pluginStatus)
        const btn=document.getElementById('primary');
        if(btn){
          btn.textContent = s2.pluginStatus==='TOPMOST' ? '取消置顶' : '置顶'
          btn.className = s2.pluginStatus==='TOPMOST' ? 'secondary' : ''
        }
      }
    })
  })
}
document.getElementById('auto').addEventListener('change',e=>{
  const on=e.target.checked
  chrome.storage.local.set({autoTopEnabled:on}).then(()=>{
    chrome.runtime.sendMessage({type:'apply-auto-switch',on})
    toast(on?'已启用自动置顶':'已关闭自动置顶', on?'ok':'off')
  })
})
document.getElementById('primary').addEventListener('click',()=>{
  chrome.storage.local.get(['pluginStatus']).then(s=>{
    const cur=s.pluginStatus
    if(cur==='TOPMOST'){
      const btn=document.getElementById('primary');
      if(btn){btn.textContent='置顶';btn.className=''}
      chrome.runtime.sendMessage({type:'manual-unset'})
      toast('请求取消置顶','off')
    }else{
      const btn=document.getElementById('primary');
      if(btn){btn.textContent='取消置顶';btn.className='secondary'}
      chrome.runtime.sendMessage({type:'manual-set'})
      toast('请求置顶','ok')
    }
  })
})
document.getElementById('add').addEventListener('click',()=>{
  const d=document.getElementById('domain').value.trim()
  if(!d) return
  chrome.storage.local.get(['whitelist']).then(s=>{
    const wl=Array.isArray(s.whitelist)?s.whitelist:[]
    if(!wl.includes(d)) wl.push(d)
    chrome.storage.local.set({whitelist:wl}).then(()=>{
      document.getElementById('domain').value=''
      render()
      toast('已加入白名单','ok')
    })
  })
})
document.getElementById('clear').addEventListener('click',()=>{
  chrome.storage.local.set({whitelist:[]}).then(()=>{render();toast('已清空白名单','off')})
})
document.getElementById('more').addEventListener('click',()=>{showAll=!showAll;render()})
document.getElementById('setup').addEventListener('click',()=>{
  const id=chrome.runtime.id
  chrome.runtime.sendNativeMessage('com.topmost.chrome_window',{command:'setup',extension_id:id},(resp)=>{
    const err = chrome.runtime.lastError?.message
    if(err) alert(err)
    else alert('已授权: '+(resp?.origin||''))
  })
})
chrome.tabs.onActivated.addListener(()=>{updateSite()})
chrome.tabs.onUpdated.addListener((tabId,changeInfo,tab)=>{if(tab&&tab.active&&changeInfo&&changeInfo.url) updateSite()})
chrome.windows.onFocusChanged.addListener(()=>{updateSite()})
chrome.storage.onChanged.addListener((changes, area)=>{
  if(area==='local' && changes.pluginStatus){
    const s=changes.pluginStatus.newValue
    setStatus(s)
    const btn=document.getElementById('primary');
    if(btn){
      btn.textContent = s==='TOPMOST' ? '取消置顶' : '置顶'
      btn.className = s==='TOPMOST' ? 'secondary' : ''
    }
  }
  if(area==='local' && changes.autoTopEnabled){
    const on = !!changes.autoTopEnabled.newValue
    const el = document.getElementById('auto')
    if(el){ el.checked = on }
    toast(on?'已启用自动置顶':'已关闭自动置顶', on?'ok':'off')
  }
})
//
render()
let showAll=false
